from datetime import datetime
from fastapi import APIRouter, Depends, Form, Request
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession
from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_stock.service.basic_service import BasicService
from module_stock.entity.vo.basic_vo import BasicQueryModel, DeleteBasicModel, BasicModel, BasicPageQueryModel
from utils.common_util import bytes2file_response
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil


basicController = APIRouter(prefix='/stock/basic', dependencies=[Depends(LoginService.get_current_user)])


@basicController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:list'))]
)
async def get_stock_basic_list(
    request: Request,
basic_page_query: BasicPageQueryModel = Depends(BasicPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    basic_page_query_result = await BasicService.get_basic_list_services(query_db, basic_page_query, is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=basic_page_query_result)

@basicController.get(
    '/all', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:all'))]
)
async def get_all_stock_basic(
    request: Request,
    query_db: AsyncSession = Depends(get_db),
):
    # 获取全量数据
    basic_page_query: BasicPageQueryModel = BasicPageQueryModel()
    basic_query_result = await BasicService.get_basic_list_services(query_db, basic_page_query, is_page=False)
    logger.info('获取成功')

    return ResponseUtil.success(rows=basic_query_result)

@basicController.get('/syncak', dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:syncak'))])
@Log(title='股票基础信息', business_type=BusinessType.OTHER)
async def syncak_stock_basic(
    request: Request,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    syncak_basic_result = await BasicService.sync_ak_services(query_db)
    logger.info(syncak_basic_result.message)

    return ResponseUtil.success(msg=syncak_basic_result.message)

@basicController.post('', dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:add'))])
@ValidateFields(validate_model='add_basic')
@Log(title='股票基础信息', business_type=BusinessType.INSERT)
async def add_stock_basic(
    request: Request,
    add_basic: BasicModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    add_basic_result = await BasicService.add_basic_services(query_db, add_basic)
    logger.info(add_basic_result.message)

    return ResponseUtil.success(msg=add_basic_result.message)


@basicController.put('', dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:edit'))])
@ValidateFields(validate_model='edit_basic')
@Log(title='股票基础信息', business_type=BusinessType.UPDATE)
async def edit_stock_basic(
    request: Request,
    edit_basic: BasicModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    edit_basic.update_by = current_user.user.user_name
    edit_basic.update_time = datetime.now()
    edit_basic_result = await BasicService.edit_basic_services(query_db, edit_basic)
    logger.info(edit_basic_result.message)

    return ResponseUtil.success(msg=edit_basic_result.message)


@basicController.delete('/{symbols}', dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:remove'))])
@Log(title='股票基础信息', business_type=BusinessType.DELETE)
async def delete_stock_basic(request: Request, symbols: str, query_db: AsyncSession = Depends(get_db)):
    delete_basic = DeleteBasicModel(symbols=symbols)
    delete_basic_result = await BasicService.delete_basic_services(query_db, delete_basic)
    logger.info(delete_basic_result.message)

    return ResponseUtil.success(msg=delete_basic_result.message)


@basicController.get(
    '/{symbol}', 
    response_model=BasicModel, 
    dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:query'))]
)
async def query_detail_stock_basic(request: Request, symbol: int, query_db: AsyncSession = Depends(get_db)):
    """
    查询股票基础信息详情
    
    相关知识点：
    - RESTful API设计 (参考文档：技术知识点.md - 10. RESTful API设计)
    - 异步编程 (参考文档：技术知识点.md - 5. 异步编程)
    
    参数：
    - request: HTTP请求对象
    - symbol: 股票代码
    - query_db: 数据库会话
    
    返回：
    - 股票基础信息详情
    """
    # 获取详情数据
    basic_detail_result = await BasicService.basic_detail_services(query_db, symbol)
    logger.info(f'获取symbol为{symbol}的信息成功')
    
    return ResponseUtil.success(data=basic_detail_result)


@basicController.post('/export', dependencies=[Depends(CheckUserInterfaceAuth('stock:basic:export'))])
@Log(title='股票基础信息', business_type=BusinessType.EXPORT)
async def export_stock_basic_list(
    request: Request,
    basic_page_query: BasicPageQueryModel = Form(),
    query_db: AsyncSession = Depends(get_db),
):
    """
    导出股票基础信息列表
    
    相关知识点：
    - RESTful API设计 (参考文档：技术知识点.md - 10. RESTful API设计)
    - 异步编程 (参考文档：技术知识点.md - 5. 异步编程)
    
    参数：
    - request: HTTP请求对象
    - basic_page_query: 导出查询参数
    - query_db: 数据库会话
    
    注解：
    - @Log: 记录操作日志
    
    返回：
    - Excel文件下载响应
    """
    # 获取全量数据
    basic_query_result = await BasicService.get_basic_list_services(
        query_db, basic_page_query, is_page=False
    )
    
    # 调用服务层导出数据
    basic_export_result = await BasicService.export_basic_list_services(basic_query_result)
    logger.info('导出股票基础信息成功')
    
    # 返回文件响应
    return ResponseUtil.streaming(data=bytes2file_response(basic_export_result))
